<template>
  <div class="createGroup">
    <div class="toolBar">
      <el-input
        v-model="searchWord"
        size="small"
        @clear="getGroupList"
        style="width: 30%"
        type="text"
        placeholder="群组名称"
        clearable
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
        <el-button
          @click="getGroupList"
          slot="append"
          icon="el-icon-search"
        ></el-button>
      </el-input>
      <el-button
        @click="addDialog"
        style="margin-left: 10px"
        size="small"
        type="primary"
        ><i class="el-icon-plus"></i> 新建群组</el-button
      >
      <el-button @click="deleteKind" size="small" type="danger"
        ><i class="el-icon-delete"></i> 删除选中</el-button
      >
    </div>
    <div class="content">
      <el-table
        border
        stripe
        size="small"
        :highlight-current-row="true"
        :data="tableData"
        style="width: 100%"
        height="490"
        @selection-change="selectDelete"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="groupName" label="群组名称"></el-table-column>
        <el-table-column prop="groupCount" label="群组人数"></el-table-column>
        <el-table-column prop="groupTypeName" label="群组类型"></el-table-column>
        <el-table-column
          prop="createUsername"
          label="群组创建人"
        ></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column align="center" label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button @click="edit(scope.row)" size="mini" type="primary"
              ><i class="el-icon-edit"></i
            ></el-button>
            <el-button
              @click="removeKind(scope.row.id)"
              size="mini"
              type="danger"
              ><i class="el-icon-delete"></i
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          small
          background
          layout="total, prev, pager, next"
          :total="total"
          @current-change="goSize"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog title="新增群组" :visible.sync="showAdd">
      <el-form size="small">
        <el-form-item label="群组名称">
          <el-input
            style="width: 70%"
            v-model="add.workGroup.groupName"
            placeholder="群组名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属组群">
          <el-radio-group v-model="kindCode" @change="getGroupTree">
            <el-radio label="bu">BU</el-radio>
            <el-radio label="dept">部门</el-radio>
          </el-radio-group>
          <el-cascader
            v-model="groupIds"
            clearable
            :options="options"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'kindName' }"
            @change="handleChange"
            style="margin-left: 10px"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="确认人">
          <el-select v-model="add.powerUserIdList" multiple filterable>
            <el-option
              v-for="(item, index) in powerList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="添加成员">
        </el-form-item>
        <el-transfer
            filterable
            filter-placeholder="请输入成员姓名"
            v-model="add.userIdList"
            :titles="['全部成员', '群组成员']"
            :data="userData"
            :props="{
              key: 'id',
              label: 'name',
            }"
          >
          </el-transfer>
        <el-form-item class="diaBtn">
          <el-button type="primary" @click="addGroup">确定</el-button>
          <el-button @click="showAdd = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import * as api from "@/js/workTimeApi";
export default {
  name: "CreateGroup",
  data() {
    return {
      searchWord: null,
      tableData: [],
      total: 0,
      deleteIdList: [],
      showAdd: false,
      showAddProjectKind: false,
      add: {
        workGroup: {},
        userIdList: [],
        powerUserIdList: [],
      },
      isEditBtn: false,
      projectTypeList: [],
      newProjectKind: null,
      pageNum: 1,
      pageSize: 10,
      projectTypeId: null,
      options: [],
      kindCode: "dept",
      groupIds: [],
      userData: [],
      powerList: [],
      groupTypeList: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1;
      },
    };
  },
  methods: {
    addDialog() {
      // this.getGroupTree();
      // this.getUserList();
      // this.getPowerUserList();
      this.add.workGroup = {};
      this.add.powerUserIdList = [];
      this.add.userIdList = []
      this.showAdd = true;
    },
    //选择用户
    // selectUser(data) {
    //   console.log(data);
    // },
    //跳页
    goSize(currentPage) {
      this.pageNum = currentPage;
      this.getProjectList();
    },
    //查询
    async getGroupList() {
      await this.getGroupTypeList();
      api
        .getGroupList({
          groupName: this.searchWord,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
        })
        .then((res) => {
          if (res.status === "success") {
            this.tableData = res.data.records;
            this.total = res.data.total;
            this.tableData.forEach((element,index) => {
                let obj = this.groupTypeList.find(value => {
                    return element.groupTypeId == value.id;
                })
                this.tableData[index].groupTypeName = obj.kindName;
            });
            // console.log("--->", this.groupTypeList);
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
        });
    },
    //选择删除
    selectDelete(data) {
      let temp = [];
      data.forEach((element) => {
        temp.push(element.id);
      });
      // console.log(temp);
      this.deleteIdList = temp;
    },
    removeKind(id) {
      this.deleteIdList = [];
      this.deleteIdList.push(id);
      this.deleteKind();
    },
    //删除
    deleteKind() {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteGroup(this.deleteIdList).then((res) => {
            if (res.status == "success") {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getGroupList();
              this.deleteIdList = [];
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addGroup() {
      this.add.workGroup.groupCount = this.add.userIdList.length;
      this.add.workGroup.createUsername = sessionStorage.getItem("username");
      this.add.workGroup.createUserId = sessionStorage.getItem("userId");
      if (this.isEditBtn) {
        api.updateGroup(this.add).then((res) => {
          if (res.status == "success") {
            this.$message({
              type: "success",
              message: "修改成功",
            });
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
          this.isEditBtn = false;
          this.showAdd = false;
        });
      } else {
        api.createGroup(this.add).then((res) => {
          if (res.status == "success") {
            this.$message({
              type: "success",
              message: "添加成功",
            });
            this.getGroupList();
          } else {
            this.$message({
              type: "error",
              message: res.message,
            });
          }
          this.showAdd = false;
        });
      }
    },
    //编辑
    edit(data) {
      // console.log(data);
      this.add.workGroup = data;
      this.getUserByGroup(data);
      this.getPowerUserByGroup(data);
      this.showAdd = true;
      this.isEditBtn = true;
    },
    //获取群组树形结构
    getGroupTree() {
      api.getGroupKindTree({ kindCode: this.kindCode }).then((res) => {
        this.options = res.data;
      });
    },
    //级联选项
    handleChange(data) {
      this.add.workGroup.groupTypeId = data[data.length - 1];
      // console.log(data[data.length - 1]);
    },
    //获取用户列表
    getUserList() {
      api.getUserList().then((res) => {
        // console.log(res);
        this.userData = res.data;
      });
    },
    //获取有审批权限的人
    getPowerUserList() {
      api.getHavePowerUserList().then((res) => {
        // console.log(res);
        this.powerList = res.data;
      });
    },
    //获取群组下用户列表
    getUserByGroup(data) {
      api.getUserByGroup({ groupId: data.id }).then((res) => {
        let temp = [];
        res.data.forEach((element) => {
          temp.push(element.userId);
        });
        // console.log(temp);
        this.add.userIdList = temp;
      });
    },
    //获取群组下审批人列表
    getPowerUserByGroup(data) {
      this.add.powerUserIdList = [];
      api.getPowerUserByGroup({ groupId: data.id }).then((res) => {
        let temp = []
        res.data.forEach(element => {
          temp.push(element.userId);
        });
        this.add.powerUserIdList = temp;
      });
    },
    //获取群组类型列表
    getGroupTypeList() {
      api.getGroupKindList({ pageNum: 1, pageSize: 500 }).then((res) => {
        // console.log(res);
        this.groupTypeList = res.data.records;
      });
    },
  },
  async mounted() {
    this.getGroupTree();
    this.getGroupList();
    this.getUserList();
    this.getPowerUserList();
  },
};
</script>
<style scoped>
.createGroup {
  padding-top: 20px;
}
.toolBar {
  display: flex;
}
.content {
  margin-top: 10px;
}
.diaBtn {
  display: flex;
  justify-content: center;
}
.pagination {
  margin-top: 10px;
  width: 100%;
  text-align: center;
}
</style>